//
//  BN_MineViewController.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-3-28.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_MineViewController.h"
#import "BN_MyInfoHelper.h"
#import "BN_PersonalInfoModifyViewController.h"

#define PATH_DOC_USERDATA [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"UserData"]

@interface BN_MineViewController () {
    BN_PersonalHostPageView *personalView_;
    BN_Mine_TeacherData *teacherData_;
    BN_Mine_ParentData *parentData_;

    UIView *medalAndCommentView_;
    BN_MyInfoHelper *myInfoHelper_;
    
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    
    NSArray *fileNameArr_;
    NSArray *cellImageArr_;
    NSInteger userType;
}

@end

@implementation BN_MineViewController

// 获取用户头像。先从本地取，如果没有再从网络拿。接下来从网络上拿到的话在保持本地，拿不到直接显示默认图片
- (void)getUserPhotoImage {
    // modify by lzc 取到本地用户头像图片
    NSString *path = [NSString stringWithFormat:@"%@/userPhoto.png",PATH_DOC_USERDATA];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        UIImage *userPhotoImage = [UIImage imageWithContentsOfFile:path];
        personalView_.userPhotoImageView.image = userPhotoImage;
    }else {
        [myInfoHelper_ queryUserInfo:^(id result, NSString *errMsg) {
            if (errMsg) {
                personalView_.userPhotoImageView.image = [UIImage imageNamed:@"userPhoto"];
            }else{
                // code...
            }
        }];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBarHidden = YES;
    [self getUserPhotoImage];
    
    // UI
    if (IOS7) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    // NSUserDefault
    [[NSUserDefaults standardUserDefaults]setInteger:10 forKey:USERDEFAULTS_KINDERSECTION];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(apSettingVc:) name:K_MINE_OPEN_SETTING_VC object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(apModifyVc:) name:K_MINE_OPEN_MODIFY_VC object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(apBabyMedalVc:) name:K_MINE_OPEN_BABY_MEDAL_VC object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(apTeacherCommentVc:) name:K_MINE_OPEN_TEACHER_COMMENT_VC object:nil];
    
    fileNameArr_ = @[@"发勋章、写周评",@"积分兑换"];
    UIImage *section2_1 = [UIImage imageNamed:@"babymedal"];
    UIImage *section2_2 = [UIImage imageNamed:@"teacherintegration"];
    cellImageArr_ = @[section2_1,section2_2];
    
    
    userInfo = [BN_UserHelper unArchiverAccountInfo];
    userType = [userInfo.userType integerValue];
    
    [self initMineTaleView];
}

#pragma mark
#pragma mark 广播触发的事件

- (void)apSettingVc:(NSNotification *)notification {
    BN_SettingViewController *settingVC = [[BN_SettingViewController alloc]init];
    [self.navigationController pushViewController:settingVC animated:YES];
}

- (void)apModifyVc:(NSNotification *)notification {
    BN_PersonalInfoModifyViewController *modifyVc = [[BN_PersonalInfoModifyViewController alloc]init];
    [self.navigationController pushViewController:modifyVc animated:YES];
}

- (void)apBabyMedalVc:(NSNotification *)notification {
    BN_MedalDisPViewController *medalDisVC = [[BN_MedalDisPViewController alloc]init];
    [self.navigationController pushViewController:medalDisVC animated:YES];
}

- (void)apTeacherCommentVc:(NSNotification *)notification {
    BN_CommentDisPViewController *commentDisVc = [[BN_CommentDisPViewController alloc]init];
    [self.navigationController pushViewController:commentDisVc animated:YES];
}
// END

- (void)waitDeve {
    BN_DiscListViewController *disVc = [[BN_DiscListViewController alloc]init];
    disVc.flg = @"nomessage";
    [self.navigationController pushViewController:disVc animated:YES];
}

#pragma mark
#pragma mark 新界面

- (void)initMineTaleView {
    _mineTaleView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT)];
    switch (userType) {
        case ENUM_ROLE_LEADER:
        {
            if (MAIN_VERSION < 7) {
                _mineTaleView.backgroundColor = [UIColor whiteColor];
            }else {
                _mineTaleView.backgroundColor = [UIColor clearColor];
            }
            _mineTaleView.delegate = self;
            _mineTaleView.dataSource = self;
            
            MJRefreshHeaderView *header = [MJRefreshHeaderView header];
            header.scrollView = _mineTaleView;
            header.delegate = self;
            _header = header;
        }
            break; // 园长UI
        case ENUM_ROLE_CLASS_TEACHER:
        {
            if (MAIN_VERSION < 7) {
                _mineTaleView.backgroundColor = [UIColor whiteColor];
            }else {
                _mineTaleView.backgroundColor = [UIColor clearColor];
            }
            _mineTaleView.delegate = self;
            _mineTaleView.dataSource = self;
            
            MJRefreshHeaderView *header = [MJRefreshHeaderView header];
            header.scrollView = _mineTaleView;
            header.delegate = self;
            _header = header;
        }
            break; // 老师UI
        case ENUM_ROLE_PARENT:
        {
            _mineTaleView.backgroundColor = APP_OBJECT_GRAY_COLOR;
            if (!parentData_) {
                parentData_ = [[BN_Mine_ParentData alloc]init];
            }
            _mineTaleView.delegate = parentData_;
            _mineTaleView.dataSource = parentData_;
            [parentData_ toReloadParentList:^(BOOL isReload) {
                if (isReload) {
                    [self cancelHintView];
                    [_mineTaleView reloadData];
                }
            }];
            [parentData_ preload];
            MJRefreshHeaderView *header = [MJRefreshHeaderView header];
            header.scrollView = _mineTaleView;
            header.delegate = parentData_;
            _header = header;
        }
            break; // 家长UI
        default:
            break;
    }
    
    switch (MAIN_VERSION) {
        case 6:
            _mineTaleView.contentInset = UIEdgeInsetsMake(0, 0, HEIGHT_TAB_BAR+20, 0);
            _mineTaleView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, HEIGHT_TAB_BAR+20, 0);
            break;
        default:
            
            _mineTaleView.contentInset = UIEdgeInsetsMake(0, 0, HEIGHT_TAB_BAR, 0);
            _mineTaleView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, HEIGHT_TAB_BAR, 0);
            break;
    }

    if ([_mineTaleView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_mineTaleView setSeparatorInset:UIEdgeInsetsZero];
    }
    _mineTaleView.backgroundColor = APP_OBJECT_GRAY_COLOR;
    [self setExtraCellLineHidden:_mineTaleView];
    [self.view addSubview:_mineTaleView];
    
    // 提示
    switch (userType) {
        case ENUM_ROLE_PARENT:
            [self viewLoadHintView];
            break;
        default:
            break;
    }
}

- (UIView *)loadNavView {
    _mineNavView = [[[NSBundle mainBundle]loadNibNamed:@"BN_Mine_NavgationView" owner:self options:nil]objectAtIndex:0];
    _mineNavView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 180-45);
    _mineNavView.backgroundImageView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 180-45);
    _mineNavView.bottomView.hidden = YES;
    _mineNavView.backgroundColor = [UIColor clearColor];
    
    // 头像
    NSString *path = [NSString stringWithFormat:@"%@/userPhoto.png",PATH_DOC_USERDATA];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        UIImage *userPhotoImage = [UIImage imageWithContentsOfFile:path];
        _mineNavView.userPhotoImageView.image = userPhotoImage;
    }
    return _mineNavView;
}

#pragma mark 
#pragma mark UITableView Delegate && DataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 && indexPath.section == 0) {
        return 180-45;
    }else {
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }else {
        return 20;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
    headerView.backgroundColor = APP_OBJECT_GRAY_COLOR;
    return headerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else {
        return 2;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"BN_SettingCell";
    BN_SettingCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"BN_SettingCell" owner:nil options:nil]objectAtIndex:0];
    }
    if (indexPath.section != 0) {
        // [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    }
    if (indexPath.section == 0 && indexPath.row == 0) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell addSubview:[self loadNavView]];
    }else {
        if (userType == ENUM_ROLE_LEADER) {
            if (indexPath.section == 1 && indexPath.row == 0) {
                cell. contentLabel.textColor = [UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1];
                cell.editing = NO;
            }
        } // 园长发勋章，写周评暂勿使用
        cell.contentLabel.text = fileNameArr_[indexPath.row];
        cell.iconImageView.image = cellImageArr_[indexPath.row];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0 && indexPath.section == 1) {
        if (userType == ENUM_ROLE_LEADER) {
            NSInteger x = SCREEN_HEIGHT-HEIGHT_TAB_BAR-15;
            NSString *disX = [NSString stringWithFormat:@"%ld",(long)x];
            [LZCHINT title:@"功能尚未开放" type:LZCSuccess duration:2 places:@[disX,disX] callBack:NULL];
        }
        
        if (userType == ENUM_ROLE_CLASS_TEACHER) {
            BN_Mine_SelectPersonViewController *selectPersonVC = [[BN_Mine_SelectPersonViewController alloc]init];
            [selectPersonVC transmitBabyInfo:^(NSString *info) {
            }];
            [self.navigationController pushViewController:selectPersonVC animated:YES];
        }
    }else if (indexPath.section >= 1 && indexPath.row >= 1) {
        [self waitDeve];
    }
}

#pragma mark
#pragma mark 刷新
- (void)upLoadFinished:(MJRefreshBaseView *)refreshView {
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 列表开始刷新，开始数据请求
    [self loadNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (_header == refreshView) {
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:0.0];
    }else {
        [self performSelector:@selector(upLoadFinished:) withObject:refreshView afterDelay:0.0];
    }
}

- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    // code...
}

- (void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state
{
    switch (state) {
        case MJRefreshStateNormal:
            break;
            
        case MJRefreshStatePulling:
            break;
            
        case MJRefreshStateRefreshing:
            break;
        default:
            break;
    }
}

#pragma mark 
#pragma mark 请求网络
- (void)loadNetData {
    // code...
    [_mineTaleView reloadData];
}

#pragma mark
#pragma mark 资源
- (void)releaseResource {
    [_header free];
    [_footer free];
    
    _header.delegate = nil;
    _footer.delegate = nil;
    
    _header = nil;
    _footer = nil;
    
    _mineTaleView.delegate = nil;
    _mineTaleView.dataSource = nil;
    _mineTaleView = nil;
    
    parentData_.mineParentListRelad = nil;
    parentData_.netArr = nil;
    parentData_.favoArr = nil;
    parentData_ = nil;
}

- (void)didReceiveMemoryWarning {
    // [self releaseResource];
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    [self releaseResource];
}

@end
